from django.db import models
from django.contrib.auth.models import User
from django.conf import settings

DOC_UPLOAD_TO = settings.DJANGO_DOCUMENTS_UPLOAD_TO


class CategoryManager(models.Manager):
	def get_user_cats(self, user):
		from django.db import connection
		cursor = connection.cursor()
		sql = """
		SELECT c.id, c.name 
		FROM django_documents_document d 
			JOIN django_documents_category c ON c.id = d.category_id
		WHERE d.owner_id = %d 
		GROUP BY c.id, c.name
		""" % user.pk
		cursor.execute(sql)
		result = []
		for r in cursor.fetchall():
			result.append({'id': int(r[0]), 'name': r[1]})
		return result



class Category(models.Model):
	name = models.CharField(max_length=128)
	
	objects = CategoryManager()
	
	def __unicode__(self):
		return self.name



class DocumentsManager(models.Manager):
	
	def _q_fields(self, word):
		from django.db.models import Q
		return Q(filename__icontains=word) \
				| Q(description__icontains=word)\
				| Q(author__icontains=word)\
				| Q(beneficient__icontains=word)
	
	def _make_query(self, search_words):
		"""
		Splits search query to a list __or__`s of django.db.models.Q objects
		Result: django.db.models.Q object
		"""
		
		query = None
		for word in search_words.split(' '):
			word = word.strip()
			if len(word) > 2:
				if not query:
					query = self._q_fields(word)
				else:
					query = query | self._q_fields(word)
		if not query:
			query = self._q_fields(search_words)
		return query 
	
	def search(self, query_str, user):
		queryset = self.filter(owner=user)
		return queryset.filter(self._make_query(query_str))



class Document(models.Model):
	owner = models.ForeignKey(User)
	category = models.ForeignKey(Category)
	filename = models.CharField(max_length=128, unique=True)
	author = models.CharField(max_length=128, null=True, blank=True)
	beneficient = models.CharField(max_length=128, null=True, blank=True)
	issued_on = models.DateTimeField(null=True, blank=True)
	description = models.TextField(null=True, blank=True)
	public = models.BooleanField(default=False)
	access_code = models.CharField(max_length=48, null=True, blank=True)
	
	objects = DocumentsManager()
	
	class Meta:
		ordering = ['-filename']



class DocumentVersion(models.Model):
	document = models.ForeignKey(Document, related_name="versions")
	version = models.CharField(max_length=10, default="1")
	timestamp = models.DateTimeField(auto_now_add=True)
	file = models.FileField(upload_to=DOC_UPLOAD_TO)
		
	
	class Meta:
		unique_together = ("document", "version")
		ordering = ['-timestamp']
